﻿using System;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using E4RPDevExpress10;
using Movements.DataSet;

namespace Movements.Controls
{
    public partial class SupplierListUserControl : XtraUserControl, IGridView, IList
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                SetGridDataSource();
                _controller.SupplierSaved += delegate { SetGridDataSource(); };                
            }
        }

        #endregion

        public SupplierListUserControl()
        {
            InitializeComponent();
            gridView.DoubleClick += GridViewDoubleClick;
        }

        #region Private Methods

        private void SetGridDataSource()
        {
            FornecedorDataSet dataSet = _controller.GetSuppliers();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Fornecedor.TableName;            
        }

        private void ShowSupplier(long documentId)
        {
            var window = new SupplierXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
        }

        #endregion
        
        #region IGridView

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "SupplierListUserControl"; }
        }

        #endregion

        public void AddDocument()
        {
            ShowSupplier(-1);
        }

        public void DeleteDocument()
        {
            throw new NotImplementedException();
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var supplier = (FornecedorDataSet.FornecedorRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (supplier == null)
                return;
            ShowSupplier(supplier.Id);
        }
       
    }
}
